import router from "@/router";
import {api_getMenuList} from "@/services/login-api";
import utils from "@/utils";


const menus = {
    state: {
        // 主菜单
        menu: JSON.parse(sessionStorage.getItem("menus")) || [],
        // 激活主菜单
        menuActive: sessionStorage.getItem("menuActive") || "/",
        // 展开子菜单
        menuOpened: sessionStorage.getItem("menuOpened") || "",
        // 动态路由添加状态
        // ! 可将变量转换成boolean类型，null、undefined和空字符串取反都为true，其余都为false。
        // !! 常常用来做类型判断，在第一步!（变量）之后再做逻辑取反运算
        routes: !!sessionStorage.getItem("menus")
    },
    getters: {
        getMenu: state => state.menu,
        getMenuActive: state => state.menuActive,
        getMenuOpened: state => state.menuOpened
    },
    mutations: {
        //获取菜单
        getMenu: (state, data) => {
            // 判断动态路由是否已添加
            if (!state.routes) {
                // 获取动态路由
                const routes = utils.getRoutes(data);
                // 添加动态路由
                router.options.routes = routes;
                router.addRoutes(routes);
                // 动态路由添加状态
                state.routes = true;
            }
            state.menu = data; // 获取菜单
            //由于vuex刷新就没了 所以咱们先存储到sessionStorage里
            sessionStorage.setItem("menus", JSON.stringify(data));
        },
        // 选择菜单
        menuSelect: (state, data) => {
            router.push(data).then(r => console.log(r) ).catch(err=>console.log(err)); // 路由跳转
            state.menuActive = data.split("?")[0]; // 激活菜单
            state.menuOpened = `/${data.split("/")[1]}`; // 展开菜单
            //由于vuex刷新就没了 所以咱们先存储到sessionStorage里
            sessionStorage.setItem("menuActive", data);
            sessionStorage.setItem("menuOpened", state.menuOpened);
        },
        // 重置菜单
        menuReset: state => {
            state.menu = [];
            state.menuActive = "/";
            state.menuOpened = "";
            sessionStorage.clear();
        }
    },
    actions: {
        //异步得到菜单
        asyngetMenu: ({commit}) => {
            api_getMenuList().then(res => {
                //放入菜单
                commit("getMenu", res.data);
                //初始菜单为/
                commit("menuSelect", "/");
            });
        }
    }

};

export default menus;



